/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lab07;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 * @author Johnny
 */
public class GUI extends JPanel implements ActionListener,DocumentListener {
  private JLabel nruzenet;
  private JTextField nrbox;
  private JButton start;
  private JButton stop;
  private JPanel top;
  private RaceCanvas center;
  private JFrame parent;

  public GUI(JFrame parent) {
    this.parent = parent;

    this.setLayout(new BorderLayout());
    top = new JPanel();
    top.setLayout(new FlowLayout());

    nruzenet = new JLabel("Autok szama");
    top.add(nruzenet);

    nrbox = new JTextField(2);
    nrbox.getDocument().addDocumentListener(this);
    top.add(nrbox);

    start = new JButton("Start");
    start.addActionListener(this);
    start.setEnabled(false);
    top.add(start);

    stop = new JButton("Stop");
    stop.addActionListener(this);
    stop.setEnabled(false);
    top.add(stop);

    this.add("North", top);


    center = null;

    this.setPreferredSize(new Dimension(1100,300));
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if (e.getSource()==start) {
      int n;
      n = Integer.parseInt(nrbox.getText());
      if (center != null) {  // Megszabadulunk a regi canvastol
        this.remove(center);
        center = null;
      }
      this.setPreferredSize(new Dimension(1100,n*100));
      parent.pack();
      center = new RaceCanvas(n,this);
      add(center);
      stop.setEnabled(true);
      start.setEnabled(false);
      nrbox.setEnabled(false);
      this.revalidate();
    } else if (e.getSource()==stop) {
      center.stopAll();
      this.finished();
    }
  }

  @Override
  public void changedUpdate(DocumentEvent e) {
    setRaceable();
  }

  @Override
  public void insertUpdate(DocumentEvent e) {
    setRaceable();
  }

  @Override
  public void removeUpdate(DocumentEvent e) {
    setRaceable();
  }

  public void setRaceable() {
    int nr;
    try {
      nr = Integer.parseInt(nrbox.getText());
      if (nr>0)
        start.setEnabled(true);
      else
        start.setEnabled(false);
    } catch (NumberFormatException ex) {
      start.setEnabled(false);
    }
  }

  public void finished() {
    stop.setEnabled(false);
    setRaceable();
    nrbox.setEnabled(true);
  }

}
